import React from "react";
import {DeviceEventEmitter, ImageBackground, ScrollView, StyleSheet, Text, TouchableOpacity, View} from "react-native";

import ModalPicker from '../components/ModalPicker';
import BookItem from "../components/BookItem";
import ctx from '../apis/';
import LoadingUtil from "../utils/LoadingUtil";
import Toast from "../components/Toast/";
import {MyStatusBar} from "../components/MyStatusBar";
import Header from "../components/Header";
import FloatButton from "../components/FloatButton";
import tool from '../utils/tool';
import {options} from '../Global'
import {storage} from '../utils/storage';
import MyLoading from "../components/MyLoading";
import {setSpText2} from "../utils/ScreenUtil";

export default class BookScreen extends React.Component {
    constructor(props) {
        super(props);
        let {book} = this.props.navigation.state.params;
        this.state = {
            book: book,//小说信息
            chapters: [],//所有章节(正序)
            displayedChapters: [],//可见的章节
            existed: false,//是否在书架

            pickerData: [],
        };
    }

    componentDidMount(): void {
        this.loadChapters();
        storage.getAllDataForKey('books')
            .then(books => {
                for (let i in books) {
                    if (this.state.book.id === books[i].id) {
                        this.setState({existed: true});
                    }
                }
            })
            .catch(err => {
                alert(err);
            });
    }

    render() {
        let {book} = this.state;
        return (
            <View style={{flex: 1}}>
                <MyStatusBar backgroundColor="#f4511e"/>
                <Header
                    headerLeftOnPress={() => this.props.navigation.goBack()}
                    headerRight={null}
                />

                <BookItem {...book}/>

                {this.renderChapters(this.state.displayedChapters)}

                <FloatButton
                    backgroundColor={'#03a9f4'}
                    bottom={90} right={20}
                    iconName={'switcher'}
                    onPress={() => {
                        this.pagePicker.open();
                    }}
                />
                <FloatButton
                    iconName={this.state.existed ? 'delete' : 'plus'}
                    backgroundColor={'#f4511e'}
                    bottom={20}
                    right={20}
                    onPress={() => {
                        if (this.state.existed) {
                            storage.removeForKeyId('books', tool.replace(book.id, '_', '~!@#'));
                            DeviceEventEmitter.emit('refreshBooks', {});
                            this.setState({existed: false});
                            Toast.show('已移出');
                        } else {
                            storage.saveForKeyId('books', tool.replace(book.id, '_', '~!@#'), book);
                            DeviceEventEmitter.emit('refreshBooks', {});
                            this.setState({existed: true});
                            Toast.show('已添加');
                        }
                    }}
                />

                <ModalPicker
                    style={{height: 0}}
                    cancelText="关闭"
                    data={this.state.pickerData}
                    ref={picker => {
                        this.pagePicker = picker;
                    }}
                    onChange={(_option) => {
                        this.changePage(_option);
                    }}
                />

                <MyLoading
                    ref={(ref) => {
                        global.mLoadingComponentRef = ref;
                    }}
                />
            </View>
        );
    }

    renderChapters = (chapters) => {
        //let {chapters} = this.state;
        let reverseChapters = tool.reverse(chapters);
        let arr = reverseChapters.map((rowData, index) => {
            return (
                <TouchableOpacity
                    key={'chapter' + index}
                    activeOpacity={0.5}
                    onPress={() => {
                        this.props.navigation.navigate('Reader', {
                            book: this.state.book,
                            // index: chapters.length - 1 - index,//当前章节位置，从0开始
                            index: this.endPos - index,//当前章节位置，从0开始(正序)
                            chapter: rowData,//当前章节
                            chapters: this.state.chapters,//章节列表(正序)
                        });
                    }}
                >
                    <View style={styles.chapterList}>
                        <Text style={{fontSize: setSpText2(15)}}>{this.endPos - index + 1} {rowData.title}</Text>
                    </View>
                </TouchableOpacity>
            );
        });
        return (
            <ScrollView
                style={{flex: 1}}
                ref={scrollView => {
                    if (scrollView !== null) {
                        setTimeout(() => {
                            scrollView.scrollTo({x: 0, y: 0, animated: true}, 1)
                        })
                    }
                }}>
                {arr}
            </ScrollView>
        )
    };

    changePage = (_option) => {
        let startPos = _option.key, endPos = _option.end;
        let displayedChapters = [];
        for (let i = startPos; i <= endPos; i++) {
            displayedChapters.push(this.state.chapters[i]);
        }
        this.startPos = startPos;
        this.endPos = endPos;
        this.setState({displayedChapters: displayedChapters});
    };

    loadChapters = () => {
        let {book} = this.state;
        LoadingUtil.showLoading();
        ctx.chapters(book.id, book.source)
            .then(chapters => {
                LoadingUtil.dismissLoading();

                // 生成ModalPicker所需要的数据
                let pickerData = [];
                for (let j = 0; j < chapters.length; j += options.pageSize) {
                    let startPos = j;
                    let endPos = (j + options.pageSize > chapters.length ? chapters.length - 1 : j + (options.pageSize - 1));
                    pickerData.push({
                        key: startPos,
                        label: (startPos + 1) + ' ~ ' + (endPos + 1),
                        end: endPos,
                    });
                }

                // 取最新的序号，如201 ~ 233
                pickerData = tool.reverse(pickerData);
                let startPos = pickerData[0].key, endPos = pickerData[0].end;
                this.startPos = startPos;
                this.endPos = endPos;
                // 显示在界面上的章节
                let displayedChapters = [];
                for (let i = startPos; i <= endPos; i++) {
                    displayedChapters.push(chapters[i]);
                }

                this.setState({
                    chapters,
                    pickerData,
                    displayedChapters: displayedChapters,
                });
            })
            .catch(err => {
                LoadingUtil.dismissLoading();
                alert(err);
            })
        ;
    };
}

const styles = StyleSheet.create({
    bottomBtnLeft: {alignItems: 'center', paddingTop: 2},
    bottomBtnRight: {alignItems: 'center', paddingTop: 2},
    bottomBtnCenter: {alignItems: 'center'},
    chapterList: {
        flexDirection: "row",
        paddingBottom: 10,
        paddingTop: 10,
        paddingLeft: 5,
        paddingRight: 5,
        borderBottomWidth: 1,
        borderBottomColor: '#ccc',
    }   ,
});